package com.storm.common.jackson

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.convertValue
import com.sun.org.slf4j.internal.LoggerFactory

inline fun <reified T, reified V>  T?.toKtData(objectMapper: ObjectMapper): V? {
    val logger =LoggerFactory.getLogger(T::class.java)
    return when {
        this == null -> null
        this is String -> {
            try {
                objectMapper.readValue<V>(this)
            } catch (e: Exception) {
                null
            }
        }
        else -> {
            try {
                objectMapper.convertValue<V>(this)
            } catch (e: Exception) {
                logger.error("序列化出错：${e.message}", e)
                null
            }
        }
    }
}

inline fun <reified T,reified V> T?.toKtList(objectMapper: ObjectMapper):List<V>{
    return when{
        this == null -> emptyList()
        this is String -> {
            try {
                objectMapper.readValue(this)
            } catch (e: Exception) {
                emptyList()
            }
        }
        else -> {
            try {
                objectMapper.convertValue(this)
            } catch (e: Exception) {
                emptyList()
            }
        }
    }

}

inline fun <reified T,reified V> T?.toKtSet(objectMapper: ObjectMapper):Set<V>{
    return when{
        this == null -> emptySet()
        this is String -> {
            try {
                objectMapper.readValue(this)
            } catch (e: Exception) {
                emptySet()
            }
        }
        else -> {
            try {
                objectMapper.convertValue(this)
            } catch (e: Exception) {
                emptySet()
            }
        }
    }

}
/**
 * 对象转字符串
 */
fun <T> T.toJson(objectMapper: ObjectMapper):String{
    return objectMapper.writeValueAsString(this)
}





